package mengrunsms

import (
	"github.com/bigwhite/gocmpp"
	"github.com/bigwhite/gocmpp/utils"
	"time"
)

func SendMsgMessage(telephone string, body string) (result interface{}, err error) {
	c := getClient()
	defer backClient(c)
	if c != nil {
		var cont string
		cont, err = cmpputils.Utf8ToUcs2(body)
		if err == nil {
			err = innerSend(c, telephone, cont)
			if err == nil {
				result, err = c.RecvAndUnpackPkt(time.Second * 3)
			} else { // 重连
				c.Disconnect()
				err = reconnect(c)
				if err == nil {
					err = innerSend(c, telephone, cont)
					if err == nil {
						result, err = c.RecvAndUnpackPkt(time.Second * 3)
					}
				}
			}
		}
	}
	return
}

func innerSend(c *cmpp.Client, telephone, cont string) (err error) {
	p := &cmpp.Cmpp2SubmitReqPkt{
		PkTotal:            1,
		PkNumber:           1,
		RegisteredDelivery: 1,
		MsgLevel:           1,
		ServiceId:          "test",
		FeeUserType:        1,
		//FeeTerminalId:      telephone,
		MsgFmt:         8,
		MsgSrc:         "900001",
		FeeType:        "01",
		FeeCode:        "0",
		ValidTime:      time.Now().Format("060102150405") + "032+",
		AtTime:         "",
		SrcId:          "900001",
		DestUsrTl:      1,
		DestTerminalId: []string{telephone},
		MsgLength:      uint8(len(cont)),
		MsgContent:     cont,
	}
	_, err = c.SendReqPkt(p)
	return
}
